package top.lyjwn.todo.weinxin.utils.apiv3;

import com.wechat.pay.contrib.apache.httpclient.WechatPayHttpClientBuilder;
import com.wechat.pay.contrib.apache.httpclient.util.PemUtil;
import org.apache.http.HttpEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.ContentType;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.util.EntityUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import top.lyjwn.todo.weinxin.WXPayConfig;
import top.lyjwn.todo.weinxin.param.WXPayParam;

import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.security.PrivateKey;
import java.security.cert.X509Certificate;
import java.util.ArrayList;
import java.util.List;

/**
 * @author luoyujie
 */
@Component
public class HttpTX {

    private static Logger logger = LoggerFactory.getLogger(HttpTX.class);

    public final static String METHOD_GET = "GET";

    public final static String METHOD_POST = "POST";

    @Autowired
    private WXPayParam wxPayParam;

    /**
     * get或者post请求
     *
     * @param requestUrl
     * @param requestJson
     * @return
     * @author luoyujie
     */
    public  String requestPost(String requestUrl, String requestJson) {
        CloseableHttpClient httpClient = null;
        CloseableHttpResponse response = null;
        HttpEntity entity = null;
        try {
            httpClient = GetHttpClient();
            HttpPost httpPost = new HttpPost(requestUrl);
            // NOTE: 建议指定charset=utf-8。低于4.4.6版本的HttpCore，不能正确的设置字符集，可能导致签名错误
            StringEntity reqEntity = new StringEntity(requestJson, ContentType.create("application/json", "utf-8"));
            httpPost.setEntity(reqEntity);
            httpPost.addHeader("Accept", "application/json");
            response = httpClient.execute(httpPost);
            entity = response.getEntity();
            return EntityUtils.toString(entity);
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            // 关闭流
            try {
                httpClient.close();
            } catch (IOException e) {
                return null;
            }
        }
        return null;
    }


    public  String requestGet(String requestUrl) {
        CloseableHttpClient httpClient = null;
        CloseableHttpResponse response = null;
        HttpEntity entity = null;

        try {
            httpClient = GetHttpClient();
            HttpGet httpGet = new HttpGet(requestUrl);
            httpGet.addHeader("Accept", "application/json");
            response = httpClient.execute(httpGet);
            entity = response.getEntity();
            return EntityUtils.toString(entity);
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            // 关闭流
            try {
                httpClient.close();
            } catch (IOException e) {
                return null;
            }
        }
        return null;
    }

    private   CloseableHttpClient httpClient;

    private  CloseableHttpClient GetHttpClient() throws UnsupportedEncodingException {

        if (httpClient!=null)
        {
            return httpClient;
        }
        //todo
        PrivateKey merchantPrivateKey = null;//WXPayConfig.PRIVATE_KEY;
        X509Certificate wechatpayCertificate = PemUtil.loadCertificate(new ByteArrayInputStream(wxPayParam.getCertificate().getBytes("utf-8")));
        List<X509Certificate> listCertificates = new ArrayList<>();
        listCertificates.add(wechatpayCertificate);

        httpClient = WechatPayHttpClientBuilder.create()
                .withMerchant(wxPayParam.getMchId(), wxPayParam.getMchSeriaLno(), merchantPrivateKey)
                .withWechatPay(listCertificates)
                .build();
        return httpClient;

    }


    /**
     * get或者post请求
     *
     * @param requestUrl
     * @param requestMethod GET or POST 需要大写
     * @param outputStr
     * @return
     * @author luoyujie
     */

    public  String request(String requestUrl, String requestMethod, String outputStr) {
        if ("POST".equals(requestMethod)) {
            return requestPost(requestUrl, outputStr);
        } else {
            return requestGet(requestUrl);
        }
    }
}
